from django.http import JsonResponse
from django.shortcuts import render, HttpResponse, redirect
import random
import requests
import json
from fake_useragent import UserAgent
from appForTest.utils import DB


# Create your views here.
def index(request):
    return render(request, 'index.html')


def user(request):
    return HttpResponse("<h2>被引入对象</h2>")


def tpl(request):
    # 普通字符串
    info = 'hellow, django'
    # 列表
    ls = ['python', 'java', 'css', 'js']
    # 字典
    dt = {
        'id': 10,
        'user': 'root',
        'pwd': '123456',
        'address': '哈尔滨',
        'addtime': '2023-07-27 13:12:10'
    }
    n = ['success', 'fail', '404']
    res = random.choice(n)
    return render(request, 'tpl.html', {'n1': info, 'n2': ls, 'n3': dt, 'res': res})


def news(request):
    url = 'http://www.chinaunicom.com.cn/api/article/NewsByIndex/2/2023/07/news'
    head = {
        'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
    }
    contest = requests.get(url, headers={"user-agent": UserAgent().random})
    # contest = requests.get(url, headers=head)
    while True:
        try:
            new_dt = contest.json()
            break
        except:
            url_list = contest.text.split('"')
            for i in url_list:
                if 'http' in i:
                    contest = requests.get(i, headers={"user-agent": UserAgent().random})
                    break
    return render(request, 'news.html', {'news': new_dt})


def admin(request):
    if request.POST.get('user') == 'admin' and request.POST.get('pwd') == '123456':
        return render(request, 'admin.html')
    else:
        return redirect("/login/")


def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    user = request.POST.get('user')
    pwd = request.POST.get('pwd')
    mysql = DB(host='119.91.139.114', user='root', passwd='Wey4pPMkyJ2d', db='django_test')
    password = mysql.findone(f'select password from tab where username="{user}"')['password']
    if password == pwd:
        return redirect('/index/')
    return redirect('/login/')


def lol(request):
    if request.GET.get('page'):
        offset = (int(request.GET.get('page')) - 1) * 20
    else:
        offset = 0
    mysql = DB(host='119.91.139.114', user='ShiXi', passwd='Wey4pPMkyJ2d', db='django_test')
    live_up = mysql.findall(f'SELECT * FROM django_test.LOL t LIMIT 20 OFFSET {offset}')

    return render(request, 'lol.html', {'live_list': live_up})


def echarts_data(request):
    return render(request, 'data.html')


def get_data(request):
    n = request.GET.get('n')
    offset = request.GET.get('offset')
    mysql = DB(host='119.91.139.114', user='ShiXi', passwd='Wey4pPMkyJ2d', db='django_test')
    result = mysql.findall(f'select author, hot_num from LOL limit {n} offset {offset}')

    json_data = {}
    author_ls = []
    hot_num_ls = []
    for dt in result:
        author_ls.append(dt['author'])
        hot_num_ls.append(dt["hot_num"])
    json_data['author'] = author_ls
    json_data['hot_num'] = hot_num_ls
    return JsonResponse(json_data)